import turbogears          as tg

from md5                   import md5
from turbogears            import identity
from whatwhat.model        import Person
from whatwhat              import utils


class PeopleController(identity.SecureResource):
    require = identity.not_anonymous()
    
    
    @tg.expose(template="whatwhat.templates.people.index")
    def index(self, show_others=0):
        groupids = utils.getGroups()
        people = Person.select(orderBy='displayName')
        person = Person.get(identity.current.user.id)
        return dict(active_section='people',
                    people=people, 
                    user_person=person, 
                    show_others=int(show_others),
                    groupids=groupids)
    
    
    @tg.expose()
    def edit_person(self, name, username, email, personid):
        person = Person.get(personid)
        print person
        person.set(displayName=name, userId=username, emailAddress=email)        
        return dict(person=person)
    
    
    @tg.expose()
    def edit_password(self, password, confirm, personid):
        person = Person.get(personid)
        print person
        person.password = md5(password).hexdigest()
        return dict(person=person)
    
    
    @tg.expose()
    def new_person(self, name, username, email, password, confirm):
        person = Person(displayName=name,
                        userId=username,
                        password=identity.current_provider.encrypt_password(password),
                        emailAddress=email)
        raise tg.redirect('/people')
